<template>
  <div class="list">
    <template v-if="users.length > 0">
        <h3>用户列表</h3>
        <el-row class="title">
            <el-col :span="2">序号</el-col>
            <el-col :span="5">账号</el-col>
            <el-col :span="6">邮箱</el-col>
            <el-col :span="5">手机号</el-col>
            <el-col :span="6">操作</el-col>
        </el-row>
        <el-row class="item" v-for="(user,index) in users" :key="user.id">
            <el-col :span="2">{{ index + 1 }}</el-col>
            <el-col :span="5">{{ user.account }}</el-col>
            <el-col :span="6">{{ user.email }}</el-col>
            <el-col :span="5">{{ user.tel }}</el-col>
            <el-col :span="6">
                <el-button type="primary" size="small" @click="detail(user.id)">详情</el-button>
                <!-- 用 ElButton 的 icon 属性为按钮绑定图标 -->
                <!-- <el-button type="primary" size="small" :icon="Edit">编辑</el-button> -->
                <el-button type="primary" size="small" @click="edit(user.id)">
                    <el-icon> <Edit /> </el-icon>
                    编辑
                </el-button>
                <el-button type="primary" size="small" @click="remove(user.id)">
                    <!-- 在 ElIcon 中使用 图标组件 -->
                    <el-icon> <Delete /> </el-icon>
                    删除
                </el-button>
            </el-col>
        </el-row>
    </template>
    <div class="none" v-else>
        暂无用户数据
    </div>
    <!-- 详情对话框 -->
    <el-dialog v-model="showDetail" :show-close="false">
        <template #title>{{user.account}}的详细信息</template>
        <ul>
            <li>id: {{ user.id }}</li>
            <li>account: {{ user.account }}</li>
            <li>email: {{ user.email }}</li>
            <li>tel: {{ user.tel }}</li>
        </ul>
        <template #footer>
            <el-button type="primary" @click="cleanup">关闭</el-button>
        </template>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog v-model="showEdit" :show-close="false">
        <template #title>编辑用户</template>
        <el-form label-position="right" label-width="120px" class="form">
            <el-form-item label="主键">
                <el-input type="text" v-model="user.id" disabled />
            </el-form-item>
            <el-form-item label="账号">
                <el-input type="text" v-model="user.account" />
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input type="text" v-model="user.email" />
            </el-form-item>
            <el-form-item label="手机号">
                <el-input type="text" v-model="user.tel" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="update">确定</el-button>
        </template>
    </el-dialog>
  </div>
</template>

<script>
// 按需导入 Element Plus 组件
import { 
  ElRow, 
  ElCol, 
  ElButton, 
  ElIcon, 
  ElDialog, 
  ElForm, 
  ElFormItem,
  ElInput 
} from 'element-plus';

// 按需导入 ElementPlus 图标组件
import { 
  Edit, 
  Delete 
} from '@element-plus/icons-vue';

export default {
  name: 'ListView',
  data(){
      return {
          users: [],
          // 把 ElementPlus 图标组件作为属性来使用
          Edit,
          message: '',
          // 控制详情对话框是否显示
          showDetail: false,
          // 用 user 来表示需要展示或修改的用户对象
          user: {},
          // 控制编辑对话框是否显示
          showEdit: false,
      }
  },
  methods: {
      cleanup(){
          this.showDetail = false;
          this.user = {}
      },
      detail(id){
        fetch(`/back/user/load/${id}`,{
            headers: { 'authorization': `Bearer ${sessionStorage.getItem( 'token' )}` }
        }).then( resp => {
            return resp.json();
        }).then( data => {
            // 注意 2201 表示查询成功
            if( data.code == 2201 ){
                this.user = data.result; // 将用户数据保存到当前组件user属性中
                this.showDetail = true ; // 让显示用户详情的对话框显示
                return; // 让当前函数立即终止
            }
        }).catch( cause => {
            console.log( cause );
        });
      },
      edit(id){
          fetch(`/back/user/load/${id}`,{
            headers: { 'authorization': `Bearer ${sessionStorage.getItem( 'token' )}` }
          }).then( resp => {
            return resp.json();
          }).then( data => {
            if( data.code == 2201 ){
                this.user = data.result;
                this.showEdit = true;
                return ;
            }
            console.log( data.desc );
          }).catch( cause => {
              console.log( cause );
          })
      },
      update(){
        console.log( this.user );
        fetch('/back/user/update',{
          method: 'post',
          headers: { 
            'authorization': `Bearer ${sessionStorage.getItem( 'token' )}`,
            'content-type': 'application/json'
          },
          body: JSON.stringify( this.user )
        }).then( resp => resp.json() )
        .then( data => {
          if( data.code == 2301 ){
            // 更新数组中指定的用户对象
            let u = this.users.find( u => u.id == this.user.id );
            Object.assign( u , this.user );
            // 关闭编辑窗口
            this.showEdit = false ;
            // 重置 user 属性
            this.user = {}
            return ;
          }
          console.log( data.desc );
        }).catch( cause => {
          console.log( cause );
        })
        
      },
      remove(id){
          fetch(`/back/user/remove/${id}`,{
            method: 'delete',
            headers: { 'authorization': `Bearer ${sessionStorage.getItem( 'token' )}` }
          }).then( resp => resp.json() )
          .then( data => {
            // 注意 2401 是 后端工程中 constant/user.js 中约定的操作代码
            if( data.code == 2401 ) {
              // 当服务端将数据库中的数据删除成功后即可删除页面上显示的数据
              let index = this.users.findIndex( u => u.id == id );
              this.users.splice( index , 1 );
              return; // 让当前函数立即结束
            }
            this.message = data.desc ;
          }).catch( cause => {
            console.log( cause );
          });
      }
  },
  // 局部注册组件
  components: {   
    ElRow, 
    ElCol, 
    ElButton, 
    ElIcon, 
    ElDialog, 
    ElForm, 
    ElFormItem,
    ElInput,
    Edit, 
    Delete 
  },
  // 生命周期钩子
  created(){
    // 尝试从 sessionStorage 中获取获取 token
    let token = sessionStorage.getItem( 'token' );
    if( !token ){
        return ; // 若 token 不存在则直接返回
    }
    // 发送异步请求并将获取到的用户数据设置到 user 数组中
    fetch( '/back/user/list' , {
        method: 'GET',
        headers: { 
            'authorization': `Bearer ${token}`
        }
    }).then( resp => resp.json() )
    .then( data => {
        // 注意 2201 是在 后端工程的 constant/user.js 中约定的操作代码
        if( data.code == 2201 ) {
            this.users = data.result ;
            return;
        }
        console.log( data.desc );
    }).catch( cause => {
        console.log( cause );
    });
  }
}
</script>

<style scoped>
.list {
    margin: 15px auto;
    border: 1px solid transparent;
    box-shadow: 0 0 20px -10px gray;
    min-height: 50px;
}

h3 { text-align: center ; }

.title {
    color: #fff;
    font-size: 18px;
    background: #66f;
}

.title,
.item {
    margin: 10px;
    line-height: 30px;
}

.item {
    border-bottom: 1px solid #dedede;
}

.none {
    text-align: center;
    line-height: 50px;
}
</style>